package top.zhongyy.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import top.zhongyy.pojo.Blog;
import top.zhongyy.pojo.Type;
import top.zhongyy.service.BlogService;
import top.zhongyy.service.TagService;
import top.zhongyy.service.TypeService;

import java.util.List;

/**
 * @Created by IntelliJ IDEA.
 * @DESC:博客首页前端控制器
 * @Author: Andy
 * @Date: 2021/3/26
 */
@Controller
public class IndexController {
    
    @Autowired
    private BlogService blogService;
    
    @Autowired
    private TypeService typeService;
    
    @Autowired
    private TagService tagService;
    
    @ApiOperation(value = "博客首页展示")
    @GetMapping("/")
    public String main(@RequestParam(defaultValue = "1", value = "pageNum") Integer pageNum, Model model) {
        PageHelper.startPage(pageNum, 5);
        List<Blog> blogs = blogService.getBlogList();
        PageInfo<Blog> pageInfo = new PageInfo<>(blogs);
        List<Type> allType = typeService.getAllType();
        model.addAttribute("recommendBlogs", blogService.getRecommend(3));
        model.addAttribute("types", allType.subList(0, 5));
        model.addAttribute("tags", tagService.getAllTags().subList(0, 5));
        model.addAttribute("page", pageInfo);
        return "index";
    }
    
    
    @ApiOperation(value = "博客搜索功能")
    @PostMapping("/search")
    public String search(Model model, @RequestParam("query") String query,
                         @RequestParam(defaultValue = "1", value = "pageNum") Integer pageNum) {
        PageHelper.startPage(pageNum, 5, "create_time desc");
        List<Blog> blogs = blogService.searchBlog(query);
        PageInfo<Blog> pageInfo = new PageInfo<>(blogs);
        model.addAttribute("page", pageInfo);
        return "search";
    }
    
    @ApiOperation(value = "博客详情")
    @GetMapping("/blog/{id}")
    public String detail(@PathVariable("id") Long id, Model model) {
        model.addAttribute("blog", blogService.getAndConvert(id));
        return "blog";
    }
    
    @GetMapping("/footer/newblog")
    public String newblogs(Model model) {
        model.addAttribute("newblogs", blogService.getRecommend(3));
        return "_fragments :: newblogList";
    }
    
}
